package com.example.blog.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;

import java.security.Key;
import java.util.Base64;
import java.util.Date;
import java.util.Map;
@Slf4j
public class JwtUtils {
    //过期时间60分钟
    private static final long expiration= 60*60*1000;
    private static final String secretString="l9VuEY5ToYQPvYN3G0Lm0Xw2tRxVLbYP3YF7JiyB/eo=";
    private static  final Key key= Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    public static String genToken(Map<String,Object>claim){
        String token= Jwts.builder()
                .setClaims(claim)//设置载荷信息
                .setExpiration(new Date(System.currentTimeMillis()+expiration))//设置过期时间
                .signWith(key)//设置签名
                .compact();  //执行方法生成token
        return  token;
    }
    //用于解析token是否正确，假如正确获取他的内部信息
    public static Claims parseToken(String token){
        if(token==null){
            return null;
        }
        JwtParser build=Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims=null;
        try{
            claims=build.parseClaimsJws(token).getBody();
        }catch (Exception e){
            log.error("解析Token失败,token:"+token);
        }
        return claims;
    }
    public static Integer getUserIdFromToken(String token){
        Claims claims=parseToken(token);
        if(claims==null){
            return null;
        }
        return (Integer) claims.get("id");
    }
}
